#!/usr/bin/env python3
# -*- coding:utf-8 -*-
u"""
@since 2019.07.30
repalce the bash script with this
"""
import os
import logging
import sys

from glob import glob
from shutil import rmtree 
from subprocess import check_call



__dir__ = os.path.abspath(os.path.dirname(__file__))
logging.basicConfig(format='%(asctime)s - %(message)s', level=logging.INFO)


def run_dca(rds, tag, param, n_jobs):
    temp_csv = rds + "_mat.csv"
    temp_dca = rds + "_dca"

    with open(os.devnull, "w+") as w:
        logging.info("Extracting")
        check_call(
            f"Rscript {os.path.join(__dir__, 'extract_count_mat.R')} {rds} {temp_csv}", 
            shell = True, 
            stderr = w, 
            stdout = w
        )


        logging.info("Run dca")

        # dca --threads=$NCPU -s 64,$param,64 $MAT $OUT
        check_call(
            f"dca --threads={n_jobs} -s 64,{param},64 {temp_csv} {temp_dca}",
            shell = True
        )

        logging.info("Adding")
        check_call(
            f"Rscript {os.path.join(__dir__, 'add_count_mat.R')} {rds} {temp_dca}/mean.tsv {tag}", 
            shell = True, 
            stderr = w, 
            stdout = w
        )
    
    if os.path.exists(temp_csv):
        os.remove(temp_csv)

    if os.path.exists(temp_dca):
        rmtree(temp_dca)


def main(rds, n_jobs = 10, param=32, tag="dca"):
    u"""
    Main
    """
    
    rds = os.path.abspath(rds)

    if os.path.isfile(rds):
        run_dca(
            rds=rds,
            tag=tag,
            param=param,
            n_jobs=n_jobs
        )
    else:
        rds = glob(os.path.join(rds, "vsMethodParams_seed_*.rds"))

        for i in rds:
            logging.info(i)

            for j in range(8, 72, 8):
                run_dca(
                    rds=i,
                    tag=f"{tag}_{j}",
                    param=j,
                    n_jobs=n_jobs
                ) 
    

if __name__ == '__main__':
    from fire import Fire
    Fire(main)

